<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { h, ref } from 'vue';
import { useAuth } from '@/hooks/business/auth';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { DICT_TYPE, getDictObj } from '@/utils/dict';
import SvgIcon from '@/components/custom/svg-icon.vue';
import {
  type Notice,
  deleteNotice,
  fetchNoticeDetail,
  fetchNoticeList,
  getFetchNoticeUrl,
  publishNotice,
  revokeNotice
} from '@/service/api';
import { useBoolean } from '~/packages/hooks/src';
import NoticeDetailModal from './modules/notice-detail-modal.vue';
import NoticeSearch from './modules/notice-search.vue';
import NoticeOperateModal from './modules/notice-operate-modal.vue';

const appStore = useAppStore();
const { hasAuth } = useAuth();

const rowDataNotice = ref<Notice>();

const { bool: noticeDetailVisible, setTrue: openNoticeDetailModal } = useBoolean();

const {
  columns,
  columnChecks,
  data,
  loading,
  mobilePagination,
  getData,
  getDataByPage,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchNoticeList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    publishStatus: null,
    title: null,
    publishTime: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 48
    },
    {
      key: 'title',
      title: $t('page.manage.notice.noticeTitle'),
      align: 'center',
      width: 200,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'type',
      title: $t('page.manage.notice.type'),
      align: 'center',
      width: 80,
      ellipsis: {
        tooltip: true
      },
      render: row => {
        if (row.type === null) {
          return '~';
        }
        const dictObj = getDictObj(DICT_TYPE.SYSTEM_NOTICE_TYPE, row.type);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'publisherName',
      title: $t('page.manage.notice.publisherName'),
      align: 'center',
      width: 150,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'level',
      title: $t('page.manage.notice.level'),
      align: 'center',
      width: 100,
      ellipsis: {
        tooltip: true
      },
      render: row => {
        if (row.status === null) {
          return null;
        }
        const dictObj = getDictObj(DICT_TYPE.SYSTEM_NOTICE_LEVEL, row.level);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'targetType',
      title: $t('page.manage.notice.targetType'),
      align: 'center',
      width: 100,
      ellipsis: {
        tooltip: true
      },
      render: row => {
        if (row.targetType === 1) {
          return <NTag type="warning">{$t('page.manage.notice.targetTypeAll')}</NTag>;
        } else if (row.targetType === 2) {
          return <NTag type="success">{$t('page.manage.notice.targetTypeUser')}</NTag>;
        }
        return null;
      }
    },
    {
      key: 'publishStatus',
      title: $t('page.manage.notice.publishStatus'),
      align: 'center',
      width: 100,
      ellipsis: {
        tooltip: true
      },
      render: row => {
        if (row.publishStatus === 0) {
          return <NTag type="info">{$t('page.manage.notice.publishStatusUnPublished')}</NTag>;
        } else if (row.publishStatus === 1) {
          return <NTag type="success">{$t('page.manage.notice.publishStatusPublished')}</NTag>;
        } else if (row.publishStatus === -1) {
          return <NTag type="warning">{$t('page.manage.notice.publishStatusRevoked')}</NTag>;
        }
        return null;
      }
    },
    {
      key: 'createTime',
      title: $t('page.manage.notice.operaTime'),
      align: 'center',
      width: 120,
      render: row => {
        if (row.publishStatus === 1) {
          return (
            <div>
              <div>
                <span>{`${$t('page.manage.notice.createTime')}: `}</span>
                <span>{row.createTime || '-'}</span>
              </div>
              <div>
                <span>{`${$t('page.manage.notice.publishTime')}: `}</span>
                <span>{row.publishTime || '-'}</span>
              </div>
            </div>
          );
        } else if (row.publishStatus === -1) {
          return (
            <div>
              <div>
                <span>{`${$t('page.manage.notice.createTime')}: `}</span>
                <span>{row.createTime || '-'}</span>
              </div>
              <div>
                <span>{`${$t('page.manage.notice.revokeTime')}: `}</span>
                <span>{row.revokeTime || '-'}</span>
              </div>
            </div>
          );
        }
        return (
          <div>
            <div>
              <span>{`${$t('page.manage.notice.createTime')}: `}</span>
              <span>{row.createTime || '-'}</span>
            </div>
          </div>
        );
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 180,
      render: row => (
        <div class="flex-center gap-8px">
          <div v-show={hasAuth('system:notice:query')}>
            <NButton type="primary" ghost size="small" onClick={() => handleNoticeDetail(row)}>
              {{
                default: () => $t('common.look'),
                icon: () => h(SvgIcon, { icon: 'ant-design:eye-outlined' })
              }}
            </NButton>
          </div>
          <div v-show={hasAuth('system:notice:publish') && row.publishStatus !== 1}>
            <NButton type="primary" ghost size="small" onClick={() => handlePublishNotice(row)}>
              {{
                default: () => $t('page.manage.notice.publish'),
                icon: () => h(SvgIcon, { icon: 'oui:push' })
              }}
            </NButton>
          </div>
          <div v-show={hasAuth('system:notice:revoke') && row.publishStatus === 1}>
            <NButton type="primary" ghost size="small" onClick={() => handleRevokeNotice(row)}>
              {{
                default: () => $t('page.manage.notice.revoke'),
                icon: () => h(SvgIcon, { icon: 'icon-park-outline:back' })
              }}
            </NButton>
          </div>
          <div v-show={hasAuth('system:notice:update') && row.publishStatus !== 1}>
            <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
              {{
                default: () => $t('common.edit'),
                icon: () => h(SvgIcon, { icon: 'ep:edit' })
              }}
            </NButton>
          </div>
          <div v-show={hasAuth('system:notice:delete')}>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" ghost size="small" disabled={row.id === 0}>
                    {{
                      default: () => $t('common.delete'),
                      icon: () => h(SvgIcon, { icon: 'ep:delete' })
                    }}
                  </NButton>
                )
              }}
            </NPopconfirm>
          </div>
        </div>
      )
    }
  ]
});

const { modelVisible, handleAdd, handleEdit, checkedRowKeys, onDeleted, editingData, fetchDataUrl, operateType } =
  useTableOperate(data, getData);

async function handleDelete(id: number) {
  // request
  const { error } = await deleteNotice(id.toString());
  await onDeleted(error);
}

function edit(id: number) {
  fetchDataUrl.value = getFetchNoticeUrl(id);
  handleEdit(id);
}

async function handleNoticeDetail(row: Notice) {
  const { error, data: noticeDetail } = await fetchNoticeDetail(row.id);
  if (!error) {
    rowDataNotice.value = noticeDetail;
    openNoticeDetailModal();
  } else {
    window.$message?.error($t('common.noData'));
  }
}

async function handlePublishNotice(row: Notice) {
  window.$dialog?.info({
    title: $t('page.manage.notice.publish'),
    content: $t('page.manage.notice.publishAffirm'),
    positiveText: $t('common.confirm'),
    negativeText: $t('common.cancel'),
    onPositiveClick: async () => {
      const { error } = await publishNotice(row.id);
      if (!error) {
        window.$message?.success($t('page.manage.notice.publishSuccess'));
        getDataByPage();
      }
    }
  });
}

async function handleRevokeNotice(row: Notice) {
  window.$dialog?.warning({
    title: $t('page.manage.notice.revoke'),
    content: $t('page.manage.notice.revokeAffirm'),
    positiveText: $t('common.confirm'),
    negativeText: $t('common.cancel'),
    onPositiveClick: async () => {
      const { error } = await revokeNotice(row.id);
      if (!error) {
        window.$message?.success($t('page.manage.notice.revokeSuccess'));
        getDataByPage();
      }
    }
  });
}
</script>

<template>
  <div class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NoticeSearch
      v-if="hasAuth('system:notice:query')"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />

    <NCard :title="$t('page.manage.notice.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          create-auth="system:notice:create"
          delete-auth="system:notice:delete"
          @add="handleAdd"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="2088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        :pagination="mobilePagination"
        class="sm:h-full"
      />
    </NCard>

    <NoticeOperateModal
      v-model:visible="modelVisible"
      :operate-type="operateType"
      :row-data="editingData"
      @submitted="getDataByPage"
    />

    <NoticeDetailModal v-model:visible="noticeDetailVisible" :row-data="rowDataNotice" />
  </div>
</template>

<style scoped></style>
